import { useStore } from '@/hooks';
import { Button, Dialog, Form, ResponsiveGrid, Icon, Drawer } from '@alifd/next';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { FieldsGrid, TitleGrid, customerModel, column } from '../stores/definitions';
import { observer } from 'mobx-react-lite';
import { toJS, observable } from 'mobx';
import AttachmentForm from './AttachmentForm';
import UploadPanel from '@/components/UploadPanel';
import TauTable from '@/components/TauTable';

const FromItem = Form.Item;
const { Cell } = ResponsiveGrid;

const DataForm = ({ customer, onCancel, modal, onSubmit, ...formProps }) => {
  const { customerStore: store } = useStore();
  const [isViewMode] = useState(modal[0] === ('view' || 'customerForm'));
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [data] = useState(() => observable({}));

  useEffect(() => {
    if (modal[1]?.startsWith?.('toClose')) {
      handleCancel();
    }
  }, [modal]);

  useEffect(() => {
    (async () => {
      const res = await store.get({ search: { username: customer?.username } });
      const userInfo = res[0];
      editCtx.origin = _.cloneDeep(userInfo);
      _.assign(data, userInfo);
    })();
  }, [modal]);

  if (!data) return <></>;

  /**
   * @description 动态回现表单数据
   * @param {*} values
   * @param {*} item 数据Items
   */
  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(data, name, value);
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  /**
   * @description 提交表单实现修改用户
   * @param {*} r formData
   */
  const handleSubmit = (values, errors) => {
    if (!_.isEmpty(errors)) {
      return;
    }
    onSubmit?.(data);
  };
  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <Form
      inline
      isPreview={isViewMode}
      {...formProps}
      value={data}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <FieldsGrid
        formData={data}
        mode={modal[0] == 'customerForm' ? 'view' : modal[0]}
        fields={(['fullname', 'mobile', 'gender', 'sourceType', 'customerInfo.customerType', 'email'])}
      />
      <FieldsGrid
        formData={data}
        mode={'view'}
        fields={(['source', 'customerInfo.registerTime', 'lastLogin'])}
      />
      <FieldsGrid
        formData={data}
        mode={modal[0] == 'customerForm' ? 'view' : modal[0]}
        fields={(['remarks'])}
      />
      <AttachmentPanel customer={data?.customerInfo} mode={modal[0]} />
      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </Form>
  );
};

const AttachmentPanel = observer(({ customer, mode }) => {
  const [curAttachment, setCurAttachment] = useState();
  const [idx, setIdx] = useState(-1); // 当前选中的附件
  const isViewMode = mode === 'view';

  useEffect(() => {
    if (customer?.attachments?.length) setIdx(0);
  }, [customer?.attachments]);

  const handleAddAttachment = () => {
    if (!customer?.attachments) customer.attachments = [];
    customer.attachments.push({ title: t`附件`, description: t`附件说明`, binaryId: [] });
    setIdx(customer.attachments.length - 1);
  };

  const handleDeleteAttachment = (i, e) => {
    customer.attachments.splice(i, 1);
    if (i === idx) setIdx(i - 1);
    e.preventDefault();
    e.stopPropagation();
  };

  return (
    <>
      <TitleGrid style={{ width: 200 }} title={<span style={{ fontSize: 16, fontWeight: 500 }}>{t`附件`}{mode !== 'view' && <Button type="primary" style={{ marginLeft: 24 }} onClick={handleAddAttachment} >{t`添加附件`}</Button>}</span>} />
      <ResponsiveGrid gap={[0, 30]} style={{ paddingLeft: 20 }}>
        <Cell colSpan={12}>
          <TauTable
            primaryKey="orderNumber"
            size="small"
            hidePagination
            tableLayout="fixed"
            dataSource={toJS(customer?.attachments)}
            cellProps={(r) => ({ style: { cursor: 'pointer', backgroundColor: idx === r ? 'var(--color-fill1-1)' : 'unset' } })}
            columns={[
              { title: '#', dataIndex: 'idx', width: 44, cell: (_, i) => i + 1 },
              column('title', {}, customerModel.customerInfo.attachments[0]),
              column('description', {}, customerModel.customerInfo.attachments[0]),
              { title: t`附件个数`, dataIndex: 'cnt', width: 84, cell: (_, i, row) => <Button type="primary" text>{row.binaryId?.length}</Button> },
            ].concat(isViewMode ? [{ align: 'left', width: 30, cell: (_, i) => (i === idx && <Icon type="arrow-right" size="xs" style={{ color: 'var(--color-line1-4)' }} />) }] : [
              {
                title: <span style={{ paddingLeft: 16 }}>{t`操作`}</span>,
                dataIndex: 'title',
                align: 'left',
                width: 110,
                cell: (_, i, row) => (
                  <span>
                    <Button type="primary" text onClick={() => setCurAttachment(row)} >{t`编辑`}</Button>
                    <span>  </span>
                    <Button type="primary" text onClick={(e) => handleDeleteAttachment(i, e)} >{t`删除`}</Button>
                    {i === idx && <Icon type="arrow-right" size="xs" style={{ marginLeft: 16, color: 'var(--color-line1-4)' }} />}
                  </span>
                ),
              },
            ])}
            onRowClick={(_, index) => setIdx(index)}
          />
        </Cell>
        <Cell colSpan={5} style={{ paddingTop: 30 }}>
          {idx >= 0 && <UploadPanel
            isPreview={isViewMode}
            prefix={`customer:${customer.id}:attachment`}
            binaryIds={idx === -1 ? [] : toJS(customer.attachments[idx]?.binaryId)}
            onUploaded={(meta) => {
              customer.attachments[idx]?.binaryId.push(meta.binaryId);
            }}
            onRemove={(info) => {
              customer.attachments[idx]?.binaryId.splice(customer.attachments[idx]?.binaryId.findIndex((r) => r == info.uid), 1);
            }}
          />}
        </Cell>
      </ResponsiveGrid>
      <Dialog
        visible={!!curAttachment}
        onCancel={() => setCurAttachment(false)}
        onClose={() => setCurAttachment(false)}
        title={t`附件`}
        style={{ width: '50%' }}
        footer={null}
      >
        <AttachmentForm
          data={curAttachment}
          onSubmit={(data) => {
            _.assign(customer.attachments[idx], data);
            setCurAttachment(false);
          }}
          onCancel={() => setCurAttachment(false)}
        />
      </Dialog>
    </>
  );
});


export default observer(DataForm);
